package com.gluxen.util;

import com.thoughtworks.xstream.XStream;

import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.gluxen.controller.WeixinController;
import com.gluxen.po.*;
import org.springframework.util.LinkedCaseInsensitiveMap;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;


public class MessageUtil extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final String MESSAGE_TEXT = "text";//文本
	public static final String MESSAGE_NEWS = "news";//语音
	public static final String MESSAGE_IMAGE = "image";//图片
	public static final String MESSAGE_VOICE = "voice";//语音
	public static final String MESSAGE_VIDEO = "video";//视频
	public static final String MESSAGE_LINK = "link";//链接
	public static final String MESSAGE_LOCATION = "location";//地理位置消息
	public static final String MESSAGE_EVENT = "event";//事件消息
	public static final String MESSAGE_SUBSCRIBE = "subscribe";//加关注事件
	public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";//取消关注事件
	public static final String MESSAGE_CLICK = "CLICK";//click类型菜单
	public static final String MESSAGE_VIEW = "VIEW";//view类型菜单
	public static final String MESSAGE_SCANCODE = "scancode_push";//扫码类型菜单
	/**
	 * 将xml文件转为map结构。
	 * @param request
	 * @return map
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static Map<String, String> XmlToMap(HttpServletRequest request)
			throws IOException, DocumentException {
		Map<String, String> map = new HashMap<String, String>();
		
		SAXReader reader = new SAXReader();
		
		InputStream ins = request.getInputStream();
		Document doc = reader.read(ins);
		
		Element root = doc.getRootElement();
		List<Element> list =  root.elements();
		
		 for(Element e : list){
			 map.put(e.getName(), e.getText());
		 }
		 ins.close();
		 
		return map;
	}
	/**
	 * 将文本消息对象转化为xml类型。
	 * @param textMessage
	 * @return
	 */
	public static String TextToMessage(TextMessage textMessage) {
		XStream xstream = new XStream();
		xstream.alias("xml",textMessage.getClass());
		return xstream.toXML(textMessage);
	}
	/**
	 * 将图文消息对象转化为xml类型。
	 * @param newsMessage
	 * @return
	 */
	public static String newsMessageToXml(NewsMessage newsMessage) {
		XStream xstream = new XStream();
		xstream.alias("xml",newsMessage.getClass());
		xstream.alias("item",new News().getClass());
		return xstream.toXML(newsMessage);
	}
	/**
	 * 将图片消息对象转化为xml类型
	 * @param imageMessage
	 * @return String
	 */
	public static String imageMessageToXml(ImageMessage imageMessage) {
		XStream xstream = new XStream();
		xstream.alias("xml",imageMessage.getClass());
		return xstream.toXML(imageMessage);
	}
	
	
	/**
	 * 将语音消息对象转化为xml类型
	 * @param imageMessage
	 * @return String
	 */
	public static String voiceMessageToXml(VoiceMessage voiceMessage) {
		XStream xstream = new XStream();
		xstream.alias("xml",voiceMessage.getClass());
		return xstream.toXML(voiceMessage);
	}
	
	
	/**
	 * 将视频消息对象转化为xml类型
	 * @param imageMessage
	 * @return String
	 */
	public static String videoMessageToXml(VideoMessage videoMessage) {
		XStream xstream = new XStream();
		xstream.alias("xml",videoMessage.getClass());
		return xstream.toXML(videoMessage);
	}
	
	
	/**
	 * 拼接文本 主菜单
	 * @return
	 */
	public static String menuText(){
		StringBuffer sBuffer  = new StringBuffer();
		sBuffer.append("欢迎您关注我的个人微信订阅号，请根据以下菜单选择您想要的服务：\n\n");
		sBuffer.append("1: 查询积分。\n");
		sBuffer.append("2: 农行介绍\n");
		sBuffer.append("3：农行主页\n");
		sBuffer.append("?: 调出此菜单\n\n");
		return sBuffer.toString();
	}
	public static String halfText(String jifen) {
		StringBuffer sBuffer  = new StringBuffer();
		sBuffer.append("尊敬的用户!\n 你当前的积分是:"+jifen+"\n"
				+"前往会员中心"+"<a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+weixinUtil.APPID+"&redirect_uri=http%3a%2f%2fgluxen.com%2fYHXM1.0%2fuser_weixinlogin.json&response_type=code&scope=snsapi_base&state=123#wechat_redirect\">进入会员中心</a> \n"
				);
		return sBuffer.toString();
	}
	public static String firstText(String jifen){
		StringBuffer sBuffer  = new StringBuffer();
		sBuffer.append("签到成功！"+"\n"
		        +"您的积分增加："+WeixinController.INTERATION_RISE+"\n"
		        +"你当前的积分是:"+jifen+"\n"
		       /* +"兑换奖品："+"<a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+weixinUtil.APPID+"&redirect_uri=http%3a%2f%2fwww.ilovetjy.xyz%2fjianglilinx%2fgift_list.json&response_type=code&scope=snsapi_base&state=123#wechat_redirect\">点击此处兑换奖品</a> \n"*/
				+"前往会员中心"+"<a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+weixinUtil.APPID+"&redirect_uri=http%3a%2f%2f120.27.110.8%2fYHXM1.0%2fuser_weixinlogin.json&response_type=code&scope=snsapi_base&state=123#wechat_redirect\">进入会员中心</a> \n"
				+"前往修改，完善资料"+"<a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+weixinUtil.APPID+"&redirect_uri=http%3a%2f%2f120.27.110.8%2fYHXM1.0%2fuser_weixinlogin.json&response_type=code&scope=snsapi_base&state=123#wechat_redirect\">前往修改资料</a> \n");
		return sBuffer.toString();
	}
	public static String secondText(String jifen){
		StringBuffer sBuffer  = new StringBuffer();
		sBuffer.append("您今天已经签到！"+"\n"
		        +"你当前的积分是:"+jifen+"\n"
		       /* +"兑换奖品："+"<a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+weixinUtil.APPID+"&redirect_uri=http%3a%2f%2fwww.ilovetjy.xyz%2fjianglilinx%2fgift_list.json&response_type=code&scope=snsapi_base&state=123#wechat_redirect\">点击此处兑换奖品</a> \n"*/
				+"前往会员中心"+"<a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+weixinUtil.APPID+"&redirect_uri=http%3a%2f%2f120.27.110.8%2fYHXM1.0%2fuser_weixinlogin.json&response_type=code&scope=snsapi_base&state=123#wechat_redirect\">进入会员中心</a> \n"
				+"前往修改，完善资料"+"<a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+weixinUtil.APPID+"&redirect_uri=http%3a%2f%2f120.27.110.8%2fYHXM1.0%2fuser_weixinlogin.json&response_type=code&scope=snsapi_base&state=123#wechat_redirect\">前往修改资料</a> \n");
		return sBuffer.toString();
	}
	
	public static String thirdText(){
		StringBuffer sBuffer  = new StringBuffer();
		sBuffer.append("请点击左下角的“键盘图标”，输入网点代码或关键字直达，还可以快捷拨打网点电话哦："+"\n"
							+"401金牛支行营业室（沙湾路）"+"\n"
							+"402成都花园支行（青羊大道）"+"\n"
							+"403荷花池支行（金牛万达旁） "+"\n"
							+"404外西支行（花牌坊北街）"+"\n"
							+"405天回支行（天回镇上街）"+"\n"
							+"406高笋塘支行（二环路北三段）"+"\n"
							+"407西郊支行（十二桥路）"+"\n"
							+"408洞子口支行（洞子口）"+"\n"
							+"409蜀鑫支行（蜀鑫路）"+"\n"
							+"410蜀西支行（蜀西路）"+"\n"
							+"411五福支行（蓉北商贸大道）"+"\n"
							+"412茶店子支行（茶店子东街）"+"\n"
							+"413国际商贸城支行（国际商贸城）"+"\n"
							+"414光华逸家分理处（万家湾光华逸家小区）"+"\n"
							+"415大湾分理处（军区总医院内）"+"\n"
							+"416蜀汉路支行（蜀蓉路）"+"\n"
							+"417星辰支行（九里堤星辰路）");
		return sBuffer.toString();
	}
	
	public static String fourthText(String url,String tel){
		StringBuffer sBuffer  = new StringBuffer();
		sBuffer.append("请点击蓝字前往--"+"\n"+url+"联系网点请拨打："+tel);
		return sBuffer.toString();
	}
	
	public static String fifthText(){
		StringBuffer sBuffer  = new StringBuffer();
		sBuffer.append("请点击蓝字前往指定营业厅--- \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=c41cde9f-7060-410e-b621-d15a0e2564e2&queueid=0&sType=0&Channel=3\">进入成都金牛支行营业厅</a> \n"
		+"联系网点请拨打：02887658812 \n"
		/*+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=2c0b70a3-5aba-4f1c-ad92-091e55df8aa3&queueid=0&sType=0&Channel=3 \">进入成都花园支行营业厅</a> \n"
		+"联系网点请拨打：02887385372 \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=93310d10-41ff-4c6e-a07e-75ff69f9a056&queueid=0&sType=0&Channel=3 \">进入成都荷花池支行营业厅</a> \n"
		+"联系网点请拨打：02883331780 \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=0c055f4f-f405-4afa-b9d9-760bcc15f83a&queueid=0&sType=0&Channel=3\">进入成都外西支行营业厅</a> \n"
		+"联系网点请拨打：02887651947 \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=07cfd019-b711-431f-adfa-9dff1a310b64&queueid=0&sType=0&Channel=3\">进入成都天回支行营业厅</a> \n"
		+"联系网点请拨打：02883572560 \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=b19c7666-79ae-45e3-ba2c-d59230f217d8&queueid=0&sType=0&Channel=3\">进入成都高笋塘支行营业厅</a> \n"
		+"联系网点请拨打：02883363025 \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=6d25e0e2-07e5-4587-87fa-ce4397fdfe86&queueid=0&sType=0&Channel=3\">进入成都西郊支行营业厅</a> \n"
		+"联系网点请拨打：02887766772 \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=123facfa-5e36-42dd-8033-62d9294bc68d&queueid=0&sType=0&Channel=3 \">进入成都洞子口支行营业厅</a> \n"
		+"联系网点请拨打：02883113505 \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=1f9a3f6c-4fba-4d84-bafc-ebfb444208ee&queueid=0&sType=0&Channel=3\">进入成都蜀鑫支行营业厅</a> \n"
		+"联系网点请拨打：02883189776 \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=6b9978e6-bfff-497a-a6c3-eeaa0a9fa09d&queueid=0&sType=0&Channel=3\">进入成都蜀西支行营业厅</a> \n"
		+"联系网点请拨打：02887313120 \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=1d290b03-200b-4792-a57c-dd42de949aa5&queueid=0&sType=0&Channel=3\">进入成都五福支行营业厅</a> \n"
		+"联系网点请拨打：02883117364 \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=3bebd011-8ccb-43d7-a89e-98c23ef11275&queueid=0&sType=0&Channel=3\">进入成都茶店子支行营业厅</a> \n"
		+"联系网点请拨打：02887520563 \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=3d59a4cd-cb10-401f-9491-12d25cced16d&queueid=0&sType=0&Channel=3\">进入成都国际商贸城支行营业厅</a> \n"
		+"联系网点请拨打：02862825786 \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=b28dbb01-1fa3-406f-8367-a99bf7335b52&sType=0\">进入成都大湾分理处营业厅</a> \n"
		+"联系网点请拨打：02883571660 \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=bc0a2d24-e95a-47db-a74f-d3442248f3ce&queueid=0&sType=0&Channel=3\">进入成都蜀汉路支行营业厅</a> \n"
		+"联系网点请拨打：02887524428 \n"
		+"<a href=\"http://app.abchina.com/MobileSite/Branch/Branch/Map?branchid=506f2e7a-281f-45b2-951c-f1e4718b13bb&queueid=0&sType=0&Channel=3\">进入成都星辰支行营业厅</a> \n"
		+"联系网点请拨打：02887604459 \n"
		+"不好意思，光华逸家网点信息暂时未更新，请直接拨打电话咨询：02864793392，或02864790887"*/);
		return sBuffer.toString();
	}
	
	/**
	 * 拼接文本消息
	 * 输入文本内容
	 * 返回xml类型对象
	 */
	public static String initTextMessage(String toUserName,String fromUserName,String text){
		String message=null;
		TextMessage text1 = new TextMessage();
		
		text1.setFromUserName(toUserName);
		text1.setToUserName(fromUserName);
		text1.setMsgType("text");
		text1.setCreateTime(new Date().getTime());
		text1.setContent(text);
		
		message = TextToMessage(text1);
		return message;
	}
	
	/**
	 * 拼接图文消息
	 * 返回xml类型对象
	 */
	public static String initNewsMessage(String toUserName,String fromUserName){
		String message = null;
		List<News> newsList = new ArrayList<News>();
		NewsMessage newsMessage = new NewsMessage();

		News news = new News();
		news.setTitle("农行介绍");
		news.setDescription("农行清江支行的介绍");
		news.setPicUrl("http://www.csfs99.com/uploads/allimg/120331/1-1203310HR6404.jpg");
		news.setUrl("http://www.abchina.com/cn/");
////
//		News news1 = new News();
//		news1.setTitle("订阅号功能介绍");
//		news1.setDescription("这个订阅号主要用于微信公众订阅号的开发，学习！这个订阅号主要用于微信公众订阅号的开发，学习！这个订阅号主要用于微信公众订阅号的开发，学习！");
//		news1.setPicUrl("http://lichangqing.duapp.com/weisxin/image/fire.jpg");
//		news1.setUrl("http://www.huajiufu.com/");

//		News news2 = new News();
//		news2.setTitle("订阅号功能介绍");
//		news2.setDescription("这个订阅号主要用于微信公众订阅号的开发，学习！这个订阅号主要用于微信公众订阅号的开发，学习！这个订阅号主要用于微信公众订阅号的开发，学习！");
//		news2.setPicUrl("http://lichangqing.duapp.com/weisxin/image/fire.jpg");
//		news2.setUrl("http://www.huajiufu.com/");
//
//		News news3 = new News();
//		news3.setTitle("订阅号功能介绍");
//		news3.setDescription("这个订阅号主要用于微信公众订阅号的开发，学习！这个订阅号主要用于微信公众订阅号的开发，学习！这个订阅号主要用于微信公众订阅号的开发，学习！");
//		news3.setPicUrl("http://lichangqing.duapp.com/weisxin/image/fire.jpg");
//		news3.setUrl("http://www.huajiufu.com/");
//
		newsList.add(news);
//		newsList.add(news1);
//		newsList.add(news2);
//		newsList.add(news3);

		newsMessage.setToUserName(fromUserName);
		newsMessage.setFromUserName(toUserName);
		newsMessage.setCreateTime(new Date().getTime());
		newsMessage.setMsgType(MESSAGE_NEWS);
		newsMessage.setArticles(newsList);
		newsMessage.setArticleCount(newsList.size());
		
		message = newsMessageToXml(newsMessage);
		return message;
	}
	
	/**
	 * 回复图片消息
	 * 
	 */
	public static String initImageMessage(String toUserName,String fromUserName){
		ImageMessage imageMessage = new ImageMessage();
		Image image = new Image();
		image.setMediaId("vOqCAIdlCILIoIHTCQimjjwEApSXNuDl-9euzPjIAWE7EeZFMnfbz9JXkVWXvCu7");
		
		imageMessage.setFromUserName(toUserName);
		imageMessage.setToUserName(fromUserName);
		imageMessage.setCreateTime(new Date().getTime());
		imageMessage.setMsgType(MESSAGE_IMAGE);
		imageMessage.setImage(image);
		
		return imageMessageToXml(imageMessage);
	}
	
	/**
	 * 组装菜单
	 * @return String类型的menu描述。
	 */
	public static String initMenu(){
		Menu menu = new Menu();
		Button button1=new Button();
		button1.setName("我的金牛");
		
		ClickButton button11 =  new ClickButton();
		button11.setName("我的会员卡");
		button11.setType("view");
		button11.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+weixinUtil.APPID+"&redirect_uri=http%3a%2f%2fgluxen.com%2fYHXM1.0%2fuser_weixinlogin.json&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
		
		ClickButton button12 = new ClickButton();
		button12.setName("新掌银下载");
		button12.setType("click");
		button12.setKey("3");	
		
		ClickButton button13 = new ClickButton();
		button13.setName("预约排号");
		button13.setType("click");
		button13.setKey("2");
		
		ClickButton button14 = new ClickButton();
		button14.setName("关于我们");
		button14.setType("view");
		button14.setUrl("http://mp.weixin.qq.com/s?__biz=MzA5MjEwMDk4Mw==&mid=502411570&idx=1&sn=3c06c871a569b211b835b85c9e80b2d1&scene=18#wechat_redirect");
		
//		ClickButton button15 = new ClickButton();
//		button15.setName("签到得积分");
//		button15.setType("click");
//		button15.setKey("1");
		
		button1.setSub_button(new Button[]{button11,button12,button13,button14});
		
		Button button2=new Button();
		button2.setName("理财信息");
		
		ClickButton button21 = new ClickButton();
		button21.setName("精品理财");
		button21.setType("view");
		button21.setUrl("http://m.abchina.com/touch/ewealthMobile/fs/");
	
		ClickButton button22 = new ClickButton();
		button22.setName("优选基金");
		button22.setType("view");
		button22.setUrl("http://m.abchina.com/touch/ewealthMobile/fund/");
		
		ClickButton button23 = new ClickButton();
		button23.setName("企业助力");
		button23.setType("view");
		button23.setUrl("http://d.eqxiu.com/s/hBp5vnHx?eqrcode=1&from=timeline&isappinstalled=0");
	
//		ClickButton button24 = new ClickButton();
//		button24.setName("借记卡");
//		button24.setType("view");
//		button24.setUrl("http://www.evereasycom.cn/Scweisite/Index/cardindex");
		
		ClickButton button25 = new ClickButton();
		button25.setName("信用卡优惠");
		button25.setType("view");
		button25.setUrl("http://mp.weixin.qq.com/s?__biz=MjM5OTExMzIwMA==&mid=2650358340&idx=1&sn=7e8dcb956e4bfe80e8719d0b7e911687&chksm=becd9adb89ba13cd24687c60e9dd2a17b7136b52de73072363f2f3adba9eabaadf50371e4a2d&mpshare=1&scene=1&srcid=1012lZ6t2cV1z63KKR9bLQ3g&from=singlemessage&isappinstalled=0#wechat_redirect");
		
		button2.setSub_button(new Button[]{button21,button22,button23,button25});
		

		Button button3=new Button();
		button3.setName("实用工具");
		
		ClickButton button31 = new ClickButton();
		button31.setName("汇率计算器");
		button31.setType("view");
		button31.setUrl("http://app.abchina.com/mobileSite/Rate/Rate/ExchangeRate");
		
		ClickButton button32 = new ClickButton();
		button32.setName("存贷计算器");
		button32.setType("view");
		button32.setUrl("http://m.abchina.com/touch/calc/");
		
		ClickButton button33 = new ClickButton();
		button33.setName("利率查询");
		button33.setType("view");
		button33.setUrl("http://m.abchina.com/touch/utility/");
		
//		ClickButton button34 = new ClickButton();
//		button34.setName("自助客服");
//		button34.setType("view");
//		button34.setUrl("http://app.abchina.com/mobileSite/KB/KB");
		

		button3.setSub_button(new Button[]{button31,button32,button33});
		
		menu.setButton(new Button[]{button1,button2,button3});
		return JSONObject.fromObject(menu).toString();
	}

	public static String initPictext(){
		PicTextArtical artical = new PicTextArtical();
		PicText[] picText = new PicText[1];
		picText[0] = new PicText();
		picText[0].setTitle("Success!");
		picText[0].setThumb_media_id("qdXM43wqPyDgY_oMDD0LF5xn0a0vjqWjo7PJtJQOakweSC8qgZoz_yFg9M9wdEmj");
		picText[0].setAuthor("jiang");
		picText[0].setDigest("heihei");
		picText[0].setShow_cover_pic("0");
		picText[0].setContent("heiheixixi");
		picText[0].setContent_source_url("www.baidu.com");
		artical.setArticles(picText);
		return JSONObject.fromObject(artical).toString();
	}

//由于测试号没有权限群发图文,只能先群发文字了。
	public static String initMessage(String content){
		Message message = new Message();

		Filter filter = new Filter();
		filter.setIs_to_all(true);

//		Mpnews mpnews = new Mpnews();
//		mpnews.setMedia_id("qdXM43wqPyDgY_oMDD0LF5xn0a0vjqWjo7PJtJQOakweSC8qgZoz_yFg9M9wdEmj");
		Text text = new Text();
		text.setContent(content);

		message.setFilter(filter);
//		message.setMpnews(mpnews);
		message.setText(text);
		message.setMsgtype("text");
		return JSONObject.fromObject(message).toString();
	}



//	public static String initPicMessage(String ToUserName, String FromUserName){
//		PicMessage message = new PicMessage();
//
////		Filter filter = new Filter();
////		filter.setIs_to_all(true);
//
//		Image image = new Image();
//		image.setMediaId("nO81-4eI9MubPp3cIGpRr9TReMwGV1Z8cpBPQXjkKLAVqLCGE8slaGe6bx8gwHT3");      //下载app二维码图片
//
//
////		message.setFilter(filter);
//		message.setIamge(image);
//		message.setMsgtype("image");
//		message.setFromUserName(ToUserName);
//		message.setToUserName(FromUserName);
//		message.setCreateTime(new Date().getTime());
//		System.out.println("-----------");
//		System.out.println(JSONObject.fromObject(message).toString());
//		
//		return JSONObject.fromObject(message).toString();
//	}



}
